﻿using System;
using System.Web;
using System.Web.Helpers;
using System.Web.WebPages;
using WebMatrix.Data;
using WebMatrix.WebData;


namespace Account
{
    /// <summary>
    /// Summary description for Register
    /// </summary>
    public static class Register
    {
        public class Model
        {
            public string Email { get; set; }
            public string Password { get; set; }
            public string ConfirmPassword { get; set; }
        }

        public class Error
        {
            public ErrorMessage Email { get; set; }
            public ErrorMessage Password { get; set; }
            public ErrorMessage ConfirmPassword { get; set; }
            public ErrorMessage AccountCreation { get; set; }
            //public ErrorMessage Captcha { get; set; }

            public Error()
            {
                Email = ErrorMessage.Nil;
                Password = ErrorMessage.Nil;
                ConfirmPassword = ErrorMessage.Nil;
                AccountCreation = ErrorMessage.Nil;
                //Captcha = ErrorMessage.Nil;
            }
        }

        public static void Init(WebPageBase web)
        {
            // Initialize general page variables
            Model model = web.Page.Model = new Model();

            // Validation
            Error error = web.Page.Errors = new Error();          
            
            // If this is a POST request, validate and process data
            if (web.IsPost)
            {
                model.Email = web.Request.Form["email"];
                model.Password = web.Request.Form["password"];
                model.ConfirmPassword = web.Request.Form["confirmPassword"];

                // Validate the user's captcha answer
                // if (!ReCaptcha.Validate("PRIVATE_KEY")) {
                //     error.Captch = web.Error("Captcha response was not correct");
                //     web.Page.IsValid = false;
                // }

                // Validate the user's email address
                if (model.Email.IsEmpty())
                {
                    error.Email = web.Error("You must specify an email address.");
                }

                // Validate the user's password and password confirmation
                if (model.Password.IsEmpty())
                {
                    error.Password = web.Error("The password cannot be blank.");
                }

                if (model.ConfirmPassword != model.Password)
                {
                    error.ConfirmPassword = web.Error("The new password and confirmation password do not match.");
                }

                // If all information is valid, create a new account
                if (web.Page.IsValid)
                {
                    // Insert a new user into the database
                    var db = Database.Open("StarterSite");

                    // Check if user already exists
                    var user = db.QuerySingle("SELECT Email FROM UserProfile WHERE LOWER(Email) = LOWER(@0)", model.Email);
                    if (user == null)
                    {
                        // Insert email into the profile table
                        db.Execute("INSERT INTO UserProfile (Email) VALUES (@0)", model.Email);

                        // Create and associate a new entry in the membership database.
                        // If successful, continue processing the request
                        try
                        {
                            bool requireEmailConfirmation = !WebMail.SmtpServer.IsEmpty();
                            var token = WebSecurity.CreateAccount(model.Email, model.Password, requireEmailConfirmation);
                            if (requireEmailConfirmation)
                            {
                                var hostUrl = web.Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);
                                var confirmationUrl = hostUrl + VirtualPathUtility.ToAbsolute("~/Account/Confirm?confirmationCode=" + HttpUtility.UrlEncode(token));

                                WebMail.Send(
                                    to: model.Email,
                                    subject: "Please confirm your account",
                                    body: "Your confirmation code is: " + token + ". Visit <a href=\"" + confirmationUrl + "\">" + confirmationUrl + "</a> to activate your account."
                                );
                            }

                            if (requireEmailConfirmation)
                            {
                                // Thank the user for registering and let them know an email is on its way
                                web.Response.Redirect("~/Account/Thanks");
                            }
                            else
                            {
                                // Navigate back to the homepage and exit
                                WebSecurity.Login(model.Email, model.Password);
                                web.Response.Redirect("~/");
                            }
                        }
                        catch (System.Web.Security.MembershipCreateUserException e)
                        {
                            web.Page.IsValid = false;
                            web.Page.AccountCreationMessage = e.ToString();
                        }
                    }
                    else
                    {
                        // User already exists
                        web.Page.IsValid = false;
                        web.Page.AccountCreationMessage = "Email address is already in use.";
                    }
                }
            }
        }
    }
}